<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>

    </style>
</head>
<body>
    正在测试ajax的get封装
    <input type="button" value="按钮1" id="btn1">
    <input type="button" value="按钮2" id="btn2">
    <input type="button" value="按钮3" id="btn3">
    <div id="box"></div>
</body>
<script>
    const btn1=document.querySelector("#btn1");
    const btn2=document.querySelector("#btn2");
    const btn3=document.querySelector("#btn3");
    btn1.onclick = function(){
        ajaxGet("http://localhost:3000/api", function(res){
            document.getElementById("box").innerHTML = res;
        },{
            a:10,
            b:20
        });
    }
    btn2.onclick = function(){
        ajaxGet("http://localhost:3000/api", function(res){
            console.log(res);
        },{
            a:10,
            b:20
        });
    }

    btn3.onclick = function(){
        ajaxGet("http://localhost:3000/api", function(res){
            alert(res);
        },{
            a:10,
            b:20
        });
    }

    function ajaxGet(url,callback,data){
        // 1.处理数据
        let str="";
        for(let i in data){
            str +=`${i}=${data[i]}&`
        }
        // 2.处理url
        url +="?"+str.slice(0,str.length-1);
        // 3.开启ajax
        const xhr=new XMLHttpRequest();
        xhr.open("get",url)
        xhr.send();
        xhr.onload=function(){
            if(xhr.status===200){
                callback(xhr.responseText);
                // 向ajax后台的程序发送xmlhttp请求的时候, 后台程序接到请求会进行处理,处理结束后,可以返回一串数据给前台,这个就是responseText 
                // console.log(xhr.responseText)
            }
        }
    }
</script>
</html>

